#!/usr/bin/env python3

#
# Copyright 2016 riteme
#

import os
import sys
import json
import urllib
import urllib.request


def save(response, save_to):
    BUFFER_SIZE = 8192  # 8MB

    file = open(save_to, "wb")
    while True:
        buf = response.read(BUFFER_SIZE)

        if len(buf) == 0:
            break

        file.write(buf)

    response.close()
    file.close()


def request(name, idx, filetype):
    requrl = "http://218.28.19.228/cogs/submit/testdata.php"

    data = {
        "filename": name,
        "point": idx,
        "io": filetype
    }

    encoded = urllib.parse.urlencode(data).encode("utf-8", "ignore")
    return urllib.request.urlopen(requrl, data = encoded)


def download(idx):
    print("(info) Downloading {}...".format(idx))

    try:
        folder = "./cogs/{}/".format(idx)
        files = os.listdir(folder)
        config = None
        for file in files:
            if file.endswith("json"):
                config = file
                break

        info = None
        with open(os.path.join(folder, config), "rb") as file:
            info = json.loads(file.read().decode("utf-8", "ignore"))

        name = info["name"]
        amount = int(info["end_id"])

        print("    * Number of testcases: {}".format(amount))
        for i in range(1, amount + 1):
            print("    * Crawling testcase {}... [in/ans]".format(i))

            try:
                in_response = request(name, i, "in")
                save(
                    in_response,
                    os.path.join(folder, "{}{}.in".format(name, i))
                )

            except Exception as e:
                print("    * \033[31mERROR\033[0m: Failed to catch {} [in]: {}".format(i, str(e)))

            try:
                out_response = request(name, i, "ans")
                save(
                    out_response,
                    os.path.join(folder, "{}{}.out".format(name, i))
                )

            except Exception as e:
                print("    * \033[31mERROR\033[0m: Failed to catch {} [ans]: {}".format(i, str(e)))

    except Exception as e:
        print("(error) Error when downloading {}: {}".format(idx, str(e)))


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: {} [START] [END]".format(sys.argv[0]))
        exit(-1)

    start = int(sys.argv[1])
    end = int(sys.argv[2])

    for i in range(start, end + 1):
        download(i)
